import os
from sc_engine.apps import messages as msgs

from sc_engine.youtube.service import parse_details
from sc_engine.repositories import Repository, use
from sc_engine.repositories.participant import PlayerTeamRepository
from sc_engine.repositories.stores import PickleFileStore

def make_app(app_name, root_config, config):
    data_directory = root_config['data_directory']

    store_filename = os.path.join(data_directory, app_name)
    store = PickleFileStore(store_filename)
    repo = Repository(store)

    app = YouTubeParseApp(repo, parse_details)

    return {
        msgs.PlayerDataAnnouncement: app.player_data_announcement,
        msgs.TeamDataAnnouncement: app.team_data_announcement,
        msgs.YouTubeFetchAnnouncement: app.youtube_fetch_announcement,
    }

class YouTubeParseApp(object):
    """Parse a you tube video title and description.

    Tries to squeeze data out of the title and description of a video fetched
    from YouTube.
    """
    def __init__(self, repo, parser):
        self.repo = repo
        self.repo.add_repository('participants', PlayerTeamRepository)
        self.parser = parser

    @use('repo', 'participants')
    def player_data_announcement(self, msg, participants):
        participants.update_player(msg.player_id, msg.name, msg.aliases)

    @use('repo', 'participants')
    def team_data_announcement(self, msg, participants):
        participants.update_team(msg.team_id, msg.name, msg.aliases)

    @use('repo', 'participants')
    def youtube_fetch_announcement(self, msg, participants_repo):
        result = self.parser(msg.title, msg.description, msg.author)

        if result['date_played'] == None or len(result['participants']) == 0:
            return

        # Ignore osl and msl games for now.
        ignore = ['osl', 'msl']
        leagues = [x for x in result.get('league', [])]
        ignored_leagues = [x for x in leagues if x in ignore]
        if len(ignored_leagues) > 0:
            return
        
        participants = result['participants']

        players, teams = participants_repo.find_participants(participants)

        return msgs.YouTubeParseAnnouncement(
            msg.video_id, msg.title, msg.author, result['part_number'][0],
            result['date_played'],teams, players, result['game_number']
        )
